<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './account.data';
  import { queryUserRole, userDepartList, saveOrUpdateUser } from '@/api/system/user/user.api';
  import { rules } from '/@/utils/helper/validator';

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        baseColProps: { span: 24 },
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        // const treeData = await getDeptList();

        updateSchema([
          { field: 'username', componentProps: { disabled: unref(isUpdate) } },
          {
            field: 'confirmPassword',
            ifShow: !unref(isUpdate),
          },
          {
            field: 'password',
            show: !unref(isUpdate),
          },
          // {
          //   field: 'selecteddeparts',
          //   componentProps: { treeData },
          // },
        ]);
        if (unref(isUpdate)) {
          const userRole = await queryUserRole({ userid: data.record.id });
          await setFieldsValue({ selectedroles: userRole });
          const userDepart = await userDepartList({ userId: data.record.id });

          if (userDepart && userDepart.length > 0) {
            await setFieldsValue({
              selecteddeparts: userDepart.map((item) => {
                return item.value;
              }),
            });
          }
          rowId.value = data.record.id;
          setFieldsValue({
            ...data.record,
          });
        } else {
          updateSchema([
            {
              field: 'username',
              dynamicRules: ({ model, schema }) =>
                rules.duplicateCheckUser(model.username, null, schema, true),
            },
            {
              field: 'phone',
              dynamicRules: ({ model, schema }) => {
                return [
                  { ...rules.duplicateCheckUser(null, model.phone, schema, true)[0] },
                  { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式有误' },
                ];
              },
            },
          ]);
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增账号' : '编辑账号'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          // if (unref(isUpdate)) {
          //   values.selecteddeparts = values.selecteddeparts.map((item) => {
          //     return item.value;
          //   });
          // }
          await saveOrUpdateUser(values, unref(isUpdate));
          closeModal();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
